package com.chinasoft.ui;

import javax.sound.sampled.*;
import java.io.IOException;

public class MyThread extends Thread{

    public void run() {
        while (true) {
                // 执行线程任务
                playMusic();
        }
    }

    public void stopThread() {
//        interrupt();
        stop();
    }

    private void playMusic()  {
        AudioInputStream ais = null;
        try {
            ais = AudioSystem.getAudioInputStream(PlayView.class.getResourceAsStream("/music/BGM.wav"));
            AudioFormat aif = ais.getFormat();
            final SourceDataLine sdl;
            DataLine.Info info = new DataLine.Info(SourceDataLine.class, aif);
            sdl = (SourceDataLine) AudioSystem.getLine(info);
            sdl.open(aif);
            sdl.start();
            FloatControl fc = (FloatControl) sdl.getControl(FloatControl.Type.MASTER_GAIN);
            // value可以用来设置音量，从0-2.0
            double value = 0.5d;
            float dB = (float) (Math.log(value == 0.0 ? 0.0001 : value) / Math.log(10.0) * 20.0);
            fc.setValue(dB);
            int nByte = 0;
            int writeByte = 0;
            final int SIZE = 1024 * 64;
            byte[] buffer = new byte[SIZE];
            while (nByte != -1 ) {
                nByte = ais.read(buffer, 0, SIZE);
                sdl.write(buffer, 0, nByte);
            }
            sdl.stop();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
